import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '@/views/auth/Login.vue'
import RegisterView from '@/views/auth/Register.vue'
import HotelManager from '../views/HotelManager.vue'
import UserManager from '@/views/manager/UserManager.vue'
import RoleManager from '@/views/manager/RoleManager.vue'
import PermissionManager from '@/views/manager/PermissionManager.vue'
import UserRoleManager from '@/views/manager/UserRoleManager.vue'
import RolePermissionManager from '@/views/manager/RolePermissionManager.vue'
import HotelManagement from '@/views/manager/HotelManagement.vue'
import RoomManager from '@/views/manager/RoomManager.vue'
import SeasonPriceManager from '@/views/manager/SeasonPriceManager.vue'
import ReviewManager from '@/views/manager/ReviewManager.vue'
import PermissionUtil from '@/utils/permission'
import HomePage from '@/views/fouter/HomePage.vue'
import PublicHotelList from '@/views/fouter/PublicHotelList.vue'
import PublicHotelDetail from '@/views/fouter/PublicHotelDetail.vue'
import PublicProfile from '@/views/fouter/PublicProfile.vue'
import PublicOrder from '@/views/fouter/PublicOrder.vue'
import MyProfile from '@/views/public/MyProfile.vue'
import MyOrders from '@/views/public/MyOrders.vue'
import EditProfile from '@/views/public/EditProfile.vue'
import NotFound from '@/views/NotFound.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'HomePage',
      component: HomePage
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView
    },
    {
      path: '/hotel',
      name: 'hotel-manager',
      component: HotelManager,
      meta: { requiresAuth: true },
      children: [
        {
          path: 'users',
          name: 'UserManager',
          component: UserManager,
          meta: { requiresSuperAdmin: true }
        },
        {
          path: 'roles',
          name: 'RoleManager',
          component: RoleManager,
          meta: { requiresSuperAdmin: true }
        },
        {
          path: 'permissions',
          name: 'PermissionManager',
          component: PermissionManager,
          meta: { requiresSuperAdmin: true }
        },
        {
          path: 'user-roles',
          name: 'UserRoleManager',
          component: UserRoleManager,
          meta: { requiresSuperAdmin: true }
        },
        {
          path: 'role-permissions',
          name: 'RolePermissionManager',
          component: RolePermissionManager,
          meta: { requiresSuperAdmin: true }
        },
        {
          path: 'hotels',
          name: 'HotelManagement',
          component: HotelManagement
        },
        {
          path: 'rooms',
          name: 'RoomManager',
          component: RoomManager
        },
        {
          path: 'season-prices',
          name: 'SeasonPriceManager',
          component: SeasonPriceManager
        },
        {
          path: 'reviews',
          name: 'ReviewManager',
          component: ReviewManager
        },
        {
          path: 'public/profile',
          name: 'MyProfile',
          component: MyProfile
        },
        {
          path: 'public/orders',
          name: 'MyOrders',
          component: MyOrders
        },
        {
          path: 'public/profile/edit',
          name: 'EditProfile',
          component: EditProfile
        }
      ]
    },
    // 前台 fouter 路由（无需登录）
    {
      path: '/fouter/hotels',
      name: 'FouterHotelList',
      component: PublicHotelList
    },
    {
      path: '/fouter/hotels/:id',
      name: 'FouterHotelDetail',
      component: PublicHotelDetail,
      props: true
    }
    ,
    {
      path: '/fouter/profile',
      name: 'PublicProfile',
      component: PublicProfile
    },
    {
      path: '/fouter/orders',
      name: 'PublicOrder',
      component: PublicOrder
    }
  ,
    {
      path: '/404',
      name: 'NotFound',
      component: NotFound
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  const requiresAuth = to.matched.some(r => r.meta && r.meta.requiresAuth)
  if (requiresAuth && !token) {
    next('/login')
    return
  }

  if (token && (to.path === '/login' || to.path === '/register')) {
    let perms = JSON.parse(localStorage.getItem('userPermissions') || '[]')
    if (!perms || perms.length === 0) {
      await PermissionUtil.syncFromServer()
      perms = JSON.parse(localStorage.getItem('userPermissions') || '[]')
    }
    const user = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const isAdminAll = perms.includes('admin:all')
    const isSystemAdmin = (user?.id === 1) || (Array.isArray(user?.roles) && user.roles.some(r => r.roleCode === 'SYSTEM_ADMIN'))
    const canViewUsers = isAdminAll || isSystemAdmin || perms.includes('user:search')
    next(canViewUsers ? '/hotel/users' : '/')
    return
  }

  // 已登录但本地权限为空，尝试从服务端同步一次
  if (token) {
    let perms = JSON.parse(localStorage.getItem('userPermissions') || '[]')
    if (!perms || perms.length === 0) {
      await PermissionUtil.syncFromServer()
      perms = JSON.parse(localStorage.getItem('userPermissions') || '[]')
    }
    // 超级管理员放行
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const isAdminAllUser = perms.includes('admin:all')
    const isSystemAdminUser = (userInfo?.id === 1) || (Array.isArray(userInfo?.roles) && userInfo.roles.some(r => r.roleCode === 'SYSTEM_ADMIN'))
    if (isAdminAllUser || isSystemAdminUser) {
      next()
      return
    }
    // 权限路由守卫：若目标路由需要特定权限，则校验
    const needPerms = to.matched.flatMap(r => (r.meta && r.meta.requiredPermissions) ? r.meta.requiredPermissions : [])
    if (needPerms.length > 0) {
      const currentPerms = perms
      const allowed = needPerms.every(p => currentPerms.includes(p))
      if (!allowed) {
        next('/404')
        return
      }
    }
    
    // 超级管理员权限检查：若目标路由需要超级管理员权限，则校验
    const requiresSuperAdmin = to.matched.some(r => r.meta && r.meta.requiresSuperAdmin)
    if (requiresSuperAdmin) {
      const isSuperAdmin = (userInfo?.id === 1) || 
                          (Array.isArray(userInfo?.roles) && userInfo.roles.some(r => r.roleCode === 'SYSTEM_ADMIN')) ||
                          perms.includes('admin:all')
      if (!isSuperAdmin) {
        next('/404')
        return
      }
    }
    // 普通用户禁止访问后台 /hotel 路由，直接返回 404
    const canAccessBackend2 = perms.includes('admin:all') || 
                              (userInfo?.id === 1) || 
                              (Array.isArray(userInfo?.roles) && userInfo.roles.some(r => r.roleCode === 'SYSTEM_ADMIN')) || 
                              perms.includes('user:search') ||
                              (Array.isArray(userInfo?.roles) && userInfo.roles.some(r => r.roleCode === 'OPERATION_ADMIN'))
    if (!canAccessBackend2 && to.path.startsWith('/hotel')) {
      next('/404')
      return
    }
    // 资料完善校验：仅对可访问后台的用户进行（普通用户不强制跳转到资料页）
    const user = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const isAdminAllPerm = perms.includes('admin:all')
    const isSystemAdminPerm = (user?.id === 1) || (Array.isArray(user?.roles) && user.roles.some(r => r.roleCode === 'SYSTEM_ADMIN'))
    const canAccessBackend = isAdminAllPerm || isSystemAdminPerm || perms.includes('user:search') || (Array.isArray(user?.roles) && user.roles.some(r => r.roleCode === 'OPERATION_ADMIN'))
    const needProfile = (!user?.realName || !user?.tel)
    const allowPaths = ['/hotel/public/profile/edit', '/hotel/public/profile', '/login']
    if (canAccessBackend && needProfile && !allowPaths.includes(to.path)) {
      next('/hotel/public/profile/edit')
      return
    }
  }

  next()
})

export default router